package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.UserService;
import com.sky.service.WorkSpaceService;
import com.sky.utils.TimeForDataUtil;
import com.sky.utils.WeChatLoginUtil;
import com.sky.vo.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;


    public TurnoverReportVO getTurnoverReport(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = begin.atStartOfDay();
        LocalDateTime endTime = end.atTime(23, 59);
        // 创建返回对象
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();

        // 从数据库获取数据
        List<Orders> turnoverReport = reportMapper.getTurnoverReport(beginTime, endTime);
        log.info("turnoverReport的值为:{}", turnoverReport);


        // 用于按日期分组存储营业额
        Map<LocalDate, Double> turnoverMap = new HashMap<>();

        // 遍历列表，按日期累加营业额
        for (Orders orders : turnoverReport) {
            if (orders != null && orders.getOrderTime() != null && orders.getAmount() != null) {
                // 提取日期
                LocalDate date = orders.getOrderTime().toLocalDate();

                // 将 BigDecimal 转换为 Double
                Double amount = orders.getAmount().doubleValue();

                // 累加营业额
                turnoverMap.put(date, turnoverMap.getOrDefault(date, 0.0) + amount);
            }
        }

        // 生成从 begin 到 end 的日期范围
        List<LocalDate> dateRange = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dateRange.add(currentDate);
            currentDate = currentDate.plusDays(1); // 增加一天
        }

        // 用于存储所有日期和营业额的列表
        List<String> allDateList = new ArrayList<>();
        List<String> allTurnoverList = new ArrayList<>();

        // 遍历日期范围，填充营业额数据
        for (LocalDate date : dateRange) {
            allDateList.add(date.toString()); // 添加日期
            allTurnoverList.add(turnoverMap.getOrDefault(date, 0.0).toString()); // 添加营业额，如果没有则为 0.0
        }

        // 将所有日期和营业额拼接成逗号分隔的字符串
        String combinedDateList = String.join(",", allDateList);
        String combinedTurnoverList = String.join(",", allTurnoverList);

        // 设置到返回对象中
        turnoverReportVO.setDateList(combinedDateList);
        turnoverReportVO.setTurnoverList(combinedTurnoverList);

        return turnoverReportVO;
    }


    public OrderReportVO getOrderReport(LocalDate begin, LocalDate end) {
        TimeForDataUtil timeForDataUtil = new TimeForDataUtil();
        List<LocalDateTime> time = timeForDataUtil.timeForData_YYMMDDHHMMSS(begin, end);
        LocalDateTime beginTime = time.get(0);
        LocalDateTime endTime = time.get(1);

        // 查询指定日期范围内的所有订单
        List<Orders> ordersList = orderMapper.list();

        // 生成完整的日期列表
        List<String> dateList = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dateList.add(currentDate.toString());
            currentDate = currentDate.plusDays(1);
        }

        // 初始化每日订单数和有效订单数的映射
        Map<String, Integer> dailyOrderCountMap = new HashMap<>();
        Map<String, Integer> dailyValidOrderCountMap = new HashMap<>();

        // 遍历订单列表，统计每日订单数和有效订单数
        for (Orders order : ordersList) {
            LocalDateTime orderTime = order.getOrderTime();
            String date = orderTime.toLocalDate().toString(); // 获取订单日期

            // 统计每日订单数
            dailyOrderCountMap.put(date, dailyOrderCountMap.getOrDefault(date, 0) + 1);

            // 统计每日有效订单数（假设状态为 5 表示已完成）
            if (order.getStatus() == 5) {
                dailyValidOrderCountMap.put(date, dailyValidOrderCountMap.getOrDefault(date, 0) + 1);
            }
        }

        // 构建订单数列表和有效订单数列表
        StringBuilder orderCountListBuilder = new StringBuilder();
        StringBuilder validOrderCountListBuilder = new StringBuilder();

        int totalOrderCount = 0;
        int validOrderCount = 0;

        for (String date : dateList) {
            int orderCount = dailyOrderCountMap.getOrDefault(date, 0);
            int validOrderCountForDate = dailyValidOrderCountMap.getOrDefault(date, 0);

            totalOrderCount += orderCount;
            validOrderCount += validOrderCountForDate;

            orderCountListBuilder.append(orderCount).append(",");
            validOrderCountListBuilder.append(validOrderCountForDate).append(",");
        }

        // 去掉最后一个逗号
        String orderCountList = orderCountListBuilder.toString().replaceAll(",$", "");
        String validOrderCountList = validOrderCountListBuilder.toString().replaceAll(",$", "");

        // 计算订单完成率并保留两位小数
        double orderCompletionRate = 0;
        if (totalOrderCount > 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }
        orderCompletionRate = new BigDecimal(orderCompletionRate).setScale(2, RoundingMode.HALF_UP).doubleValue();

        // 构建返回结果
        OrderReportVO report = new OrderReportVO();
        report.setDateList(String.join(",", dateList));
        report.setOrderCompletionRate(orderCompletionRate);
        report.setOrderCountList(orderCountList);
        report.setTotalOrderCount(totalOrderCount);
        report.setValidOrderCount(validOrderCount);
        report.setValidOrderCountList(validOrderCountList);

        return report;
    }

    public SalesTop10ReportVO getGoodsSales(LocalDate begin, LocalDate end) {
        TimeForDataUtil timeForDataUtil = new TimeForDataUtil();
        List<LocalDateTime> localDateTimes = timeForDataUtil.timeForData_YYMMDDHHMMSS(begin, end);
        List<String> dateList = dateList(begin, end);
        LocalDateTime beginTime = localDateTimes.get(0); // 例如：2025-03-15T00:00:00
        LocalDateTime endTime = localDateTimes.get(1);   // 例如：2025-03-15T23:59:59

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(Orders.COMPLETED);

        // 查询已完成状态的订单
        List<Orders> listOrders = orderMapper.pageQuery(ordersPageQueryDTO);

        // 筛选出在指定时间范围内的订单
        List<Orders> filteredOrders = listOrders.stream()
                .filter(order -> order.getOrderTime().isAfter(beginTime)
                        && order.getOrderTime().isBefore(endTime))
                .collect(Collectors.toList());

        // 如果没有订单，返回 null
        if (filteredOrders.isEmpty()) {
            return null;
        }

        // 提取订单ID列表
        List<Long> ids = new ArrayList<>();
        for (Orders orders : filteredOrders) {
            ids.add(orders.getId());
        }

        // 根据订单ID查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(ids);

        // 使用 Map 统计每个商品的销量
        Map<String, Integer> productSalesMap = new HashMap<>();

        // 遍历订单详情，统计每个商品的销量
        for (OrderDetail orderDetail : orderDetails) {
            String name = orderDetail.getName();
            int number = orderDetail.getNumber();

            // 如果商品名称已经存在，累加销量；否则，初始化销量
            productSalesMap.put(name, productSalesMap.getOrDefault(name, 0) + number);
        }

        // 将商品名称和销量分别添加到 nameList 和 numberList 中
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>(); // 用于存储销量的字符串列表

        // 按销量降序排序并保留前10个商品
        List<Map.Entry<String, Integer>> sortedEntries = productSalesMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(10) // 限制为前10个商品
                .collect(Collectors.toList());

        for (Map.Entry<String, Integer> entry : sortedEntries) {
            nameList.add(entry.getKey());
            numberList.add(String.valueOf(entry.getValue())); // 将销量转换为字符串
        }

        // 将商品名称列表和销量列表转换为逗号分隔的字符串
        String nameListStr = String.join(",", nameList);
        String numberListStr = String.join(",", numberList);

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        // 设置返回的DTO
        salesTop10ReportVO.setNameList(nameListStr);
        salesTop10ReportVO.setNumberList(numberListStr); // 设置销量列表为逗号分隔的字符串

        return salesTop10ReportVO;
    }




    /**
     * 日期生成
     *
     * @param begin
     * @param end
     * @return
     */
    private List<String> dateList(LocalDate begin, LocalDate end) {
        // 生成完整的日期列表
        List<String> dateList = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dateList.add(currentDate.toString());
            currentDate = currentDate.plusDays(1);
        }
        return dateList;
    }
}
